package com.jh.user.controller.model;

import cn.jh.common.exception.ServiceException;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.collect.Maps;
import com.google.common.collect.Range;
import com.jh.user.pojo.enums.ThirdPayType;
import io.jsonwebtoken.lang.Strings;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * @author Yichuan
 * @version 1.0
 */
public class ThirdPayRateRequest {

    private Long brandId;
    private String type;
    private List<RangeRateModel> ranges;

    @JsonIgnore
    private transient ThirdPayType payType;
    @JsonIgnore
    private transient Map<Range<BigDecimal>, BigDecimal> rangeData;

    public ThirdPayRateRequest() {
    }

    public Long getBrandId() {
        return brandId;
    }

    public void setBrandId(Long brandId) {
        this.brandId = brandId;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public List<RangeRateModel> getRanges() {
        return ranges;
    }

    public void setRanges(List<RangeRateModel> ranges) {
        this.ranges = ranges;
    }

    public ThirdPayType getPayType() {
        return payType;
    }

    public void setPayType(ThirdPayType payType) {
        this.payType = payType;
    }

    public Map<Range<BigDecimal>, BigDecimal> getRangeData() {
        return rangeData;
    }

    public void setRangeData(Map<Range<BigDecimal>, BigDecimal> rangeData) {
        this.rangeData = rangeData;
    }

    public Map<Range<BigDecimal>, BigDecimal> ofRanges() {
        if (getRanges() == null || getRanges().isEmpty()) {
            return Maps.newHashMap();
        }
        Map<Range<BigDecimal>, BigDecimal> rangeData = Maps.newHashMap();
        for (RangeRateModel model: getRanges()) {
            if (model.getLower() != null && model.getLower().compareTo(BigDecimal.ZERO) < 0) {
                throw new ServiceException("下限值设置有误");
            }
            if (model.getUpper() != null && model.getUpper().compareTo(BigDecimal.ZERO) < 0) {
                throw new ServiceException("上限值设置有误");
            }
            Range<BigDecimal> range = model.ofRange();
            if (range == null) continue;
            rangeData.put(range, model.getAgentRate());
        }
        return rangeData;
    }

    public void validation() {
        if (getBrandId() == null) {
            throw new ServiceException("贴牌id不能为空");
        }
        if (!Strings.hasText(getType())) {
            throw new ServiceException("类型不能为空");
        }
        ThirdPayType payType = ThirdPayType.of(getType());
        if (payType == null) {
            throw new ServiceException("无效的类型");
        }
        setPayType(payType);
        setRangeData(ofRanges());
        if (getRangeData().isEmpty()) {
            throw new ServiceException("费率设置异常");
        }
    }
}
